import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import '../ads/ads_const.dart';
import '../ads/ads_utils.dart';
import '../api/api_service.dart';
import '../api/bean/config_bean.dart';
import '../plugin/native_bridge.dart';
import '../plugin/ts_plugin.dart';
import '../usersp/user_sp.dart';
import '../../utils/k_log.dart';
import '../utils/json_util.dart';
import 'app_const.dart';

class AppConfig {
  static Future initAds({
    required Function() onNextPage,
    required Function(int? riseId) onRiseId,
  }) async {
    if (Platform.isAndroid) {
      _initAndroid(
        onNextPage: onNextPage,
        onRiseId: onRiseId,
      );
    } else {
      _initIOS(
        onNextPage: onNextPage,
        onRiseId: onRiseId,
      );
    }
  }

  //初始化Android
  static Future _initAndroid({
    required Function() onNextPage,
    required Function(int? riseId) onRiseId,
  }) async {
    //是否首次安装
    var isFirstApp = await UserSp.instance.isFirstApp();
    //0关闭 1开启
    KLog.d("AppConfigLog 是否是第一次安装 isFirstApp $isFirstApp");
    if (isFirstApp) {
      UserSp.instance.putIsFirstApp(false);
      //保存oaId
      await UserSp.instance.saveOaId();
      await UserSp.instance.saveOaIdU();
      await UserSp.instance.saveOaIdH();
      //更新上报信息
      var oaId = await UserSp.instance.getOaId();
      var oaIdU = await UserSp.instance.getOaIdU();
      var oaIdH = await UserSp.instance.getOaIdH();
      KLog.d("AppConfigLog oaId: $oaId oaIdU: $oaIdU  oaIdH: $oaIdH");
      ApiService().appInstall().then((configBean) {
        //初始化广告SDK
        _initAd(
          configBean?.data,
          onNextPage: onNextPage,
          onRiseId: onRiseId,
        );
      });
    } else {
      UserSp.instance.putIsFirstApp(false);
      //第二次根据配置直接初始化
      var config = await UserSp.instance.getAppConfig();
      //OaId
      var oaId = await UserSp.instance.getOaId();
      if (oaId.isEmpty) {
        //保存oaId
        await UserSp.instance.saveOaId();
      }

      //oaIdU
      var oaIdU = await UserSp.instance.getOaIdU();
      if (oaIdU.isEmpty) {
        await UserSp.instance.saveOaIdU();
      }

      //oaIdH
      var oaIdH = await UserSp.instance.getOaIdH();
      if (oaIdH.isEmpty) {
        await UserSp.instance.saveOaIdH();
      }

      KLog.d("AppConfigLog === oaId: $oaId oaIdU: $oaIdU  oaIdH: $oaIdH");

      if (oaId.isNotEmpty || oaIdU.isNotEmpty || config == null) {
        ApiService().appInstall().then((configBean) {
          //初始化广告SDK
          _initAd(
            configBean?.data,
            onNextPage: onNextPage,
            onRiseId: onRiseId,
          );
        });
      } else {
        ApiService().getAppConfig().then((configBean) {
          //初始化广告SDK
          _initAd(
            configBean?.data,
            onNextPage: onNextPage,
            onRiseId: onRiseId,
          );
        });
      }
    }
  }

  static Future _initIOS({
    required Function() onNextPage,
    required Function(int? riseId) onRiseId,
  }) async {
    await AdsUtils.requestIDFA();
    //是否首次安装
    var isFirstApp = await UserSp.instance.isFirstApp();
    //0关闭 1开启
    KLog.d("AppConfigLog 是否是第一次安装 isFirstApp $isFirstApp");
    if (isFirstApp) {
      KLog.d('AppConfigLog 第一次安装 IOS端 ');
      var jsonStr = await NativeBridge().getDeviceInfo();
      UserSp.instance.putIsFirstApp(false);
      KLog.d(
          'AppConfigLog 第一次安装 IOS端 ==== 从原生获取的数据 getInstallInfo ==== $jsonStr');
      if (jsonStr == '' || jsonStr.isEmpty || jsonStr.contains('error')) {
        onNextPage.call();
        return;
      }
      ConfigBean? configBean =
      JsonUtil.getObject(jsonStr, (e) => ConfigBean.fromJson(e));
      UserSp.instance.saveAppConfig(infoEntity: configBean);
      //初始化广告SDK
      _initAd(
        configBean,
        onNextPage: onNextPage,
        onRiseId: onRiseId,
      );
    } else {
      //第二次根据配置直接初始化
      var config = await UserSp.instance.getAppConfig();
      if (config == null) {
        KLog.d('AppConfigLog IOS端 ');
        var jsonStr = await NativeBridge().getDeviceInfo();
        UserSp.instance.putIsFirstApp(false);
        KLog.d('AppConfigLog IOS端 ==== 从原生获取的数据 getInstallInfo ==== $jsonStr');
        if (jsonStr == '' || jsonStr.isEmpty || jsonStr.contains('error')) {
          onNextPage.call();
          return;
        }
        ConfigBean? configBean =
        JsonUtil.getObject(jsonStr, (e) => ConfigBean.fromJson(e));
        UserSp.instance.saveAppConfig(infoEntity: configBean);
        //初始化广告SDK
        _initAd(
          configBean,
          onNextPage: onNextPage,
          onRiseId: onRiseId,
        );
      } else {
        ApiService().getAppConfig().then((configBean) {
          //初始化广告SDK
          _initAd(
            configBean?.data,
            onNextPage: onNextPage,
            onRiseId: onRiseId,
          );
        });
      }
    }
  }

  static void _initAd(
      ConfigBean? configBean, {
        required Function() onNextPage,
        required Function(int? riseId) onRiseId,
      }) async {
    //初始化友盟
    initUMeng(AppConst.umengAppKey, AppConst.channel);
    //初始化融合归因
    TsPlugin.bDConvertInit();
    var adSwitch = configBean?.adSwitch?.toInt() ?? 0;
    //返回自增ID
    onRiseId(configBean?.riseId?.toInt() ?? 0);

    KLog.d("AppConfigLog getAppConfig djId: ${configBean?.djId}");
    KLog.d("AppConfigLog configBean ${configBean?.toJson()}");
    KLog.d("AppConfigLog adSwitch $adSwitch");
    KLog.d("AppConfigLog isOpenAds ${AdsConst.isOpenAds}");
    KLog.d("AppConfigLog csjCheckFlag ${configBean?.csjCheckFlag}");

    if (AppConst.isCSJ) {
      AdsConst.isOpenAds = true;
      KLog.d("AppConfigLog CSJ审核模式打开 ${configBean?.csjCheckFlag}");
    } else {
      //广告是否开启
      AdsConst.isOpenAds = (adSwitch == 1);
    }


    // if(kDebugMode){
    //   AdsConst.isOpenAds = false;
    // }

    //如果配置关闭
    if (AdsConst.isOpenAds) {
      KLog.d("AppConfigLog 初始化广告...");
      try {
        //初始化广告监听
        AdsUtils.setAdEvent();
        //初始化广告
        var value = await AdsUtils.initAd();
        KLog.d("AppConfigLog 初始化广告结果 $value");
        if (value) {



          //展示开屏
          //是否是CSJ 并且是审核模式
          if (AppConst.isCSJ && configBean?.csjCheckFlag == 1) {
            //审核模式 开屏后  广告关闭
            AdsConst.isOpenAds = false;
            var isAd = await AdsUtils.showSplashAdCSJ();
            KLog.d("AppConfigLog 开屏回调结果CSJ  $isAd");
            if (!isAd) {
              onNextPage.call();
            }
          } else {

            //12小时只弹4次逻辑
            var count = await UserSp.instance.getKpCount();
            var countTime = await UserSp.instance.getKpCountTime();
            if (count >= 4 &&
                (DateTime.now().millisecondsSinceEpoch - countTime) < 43200000) {
              await Future.delayed(const Duration(seconds: 1));
              onNextPage.call();
              return;
            }

            if (count >= 4) {
              UserSp.instance.putKpCount(0);
              UserSp.instance.putKpCountTime(0);
            }

            var isAd = await AdsUtils.showSplashAd();
            KLog.d("AppConfigLog 开屏回调结果 $isAd");
            if (!isAd) {
              onNextPage.call();
            }
            //预加载
            AdsUtils.preload();
          }
        } else {
          onNextPage.call();
        }
      } catch (e) {
        onNextPage.call();
      }
    } else {
      KLog.d("AppConfigLog 广告关闭 直接进入");
      onNextPage.call();
    }
  }

  //初始化友盟
  static Future<bool> initUMeng(String umengAppKey, String channel) async {
    try {
      UmengCommonSdk.initCommon(umengAppKey, "", channel).then((value) {
        KLog.d("AppConfigLog UMLog: ${value.toString()}");
      });
      //设置自动收集
      KLog.d("AppConfigLog UMLog: 设置自动收集");
      UmengCommonSdk.setPageCollectionModeAuto();
      return true;
    } catch (e) {
      return false;
    }
  }
}
